package com.kkd.kkdapp.http.manager;

import java.lang.reflect.Type;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.kkd.kkdapp.BaseApplication;
import com.kkd.kkdapp.activity.LoginActivity;
import com.kkd.kkdapp.android_async_http.AsyncHttpClient;
import com.kkd.kkdapp.android_async_http.AsyncHttpResponseHandler;
import com.kkd.kkdapp.android_async_http.RequestHandle;
import com.kkd.kkdapp.android_async_http.RequestParams;
import com.kkd.kkdapp.db.app.model.User;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;

public class KkdHttpClient {
	
	public static final int SUCCESS = 0; // 请求成功
	public static final int TOKEN_OUT = -2; // token 失效
	public static final int RESOLUTION_EXCEPTION = -1000; // 解析异常
	public static final int NO_NET = -1001; // 无网络
	
	private static AsyncHttpClient client = new AsyncHttpClient();
	private static KkdHttpClient instance;

	public static KkdHttpClient getInstance() {
		if (instance == null) {
			instance = new KkdHttpClient();
			client.setTimeout(60000);
			client.setMaxConnections(20);
		}
		return instance;
	}
	
	/************************************
	 * 
	 * 发送请求，解析所有返回字段,保证失败返回的描述严格不为空
	 * 
	 *******************************/
	public void post(String url, RequestParams params,final HttpCallBack callback,
			final Type type) {

		if (!AppUtil.isConnect(BaseApplication.getInstance())) {
			callback.onFailure(NO_NET, "似乎没有网络");
			return;
		}
		client.post(url, params, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] responseBody) {
				try {
					String responseString = new String(responseBody);
					// LogUtil.e("responseString", responseString);
					JSONObject json = new JSONObject(responseString);
					int code = json.getInt("code");
					if (code == TOKEN_OUT) {
						callback.onFailure(code, "token失效");
						// token失效了，跳转到登陆界面
						PreferenceUtils.getInstance().clearSharedPreferences(
								BaseApplication.getInstance());
						BaseApplication.getInstance().exitGestureActivity();
						User.delCurUser();
						Intent intent = new Intent(BaseApplication
								.getInstance(), LoginActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
								| Intent.FLAG_ACTIVITY_NEW_TASK);
						BaseApplication.getInstance().startActivity(intent);
					} else if (code == SUCCESS) {

						// 请求成功
						Gson mGson = new Gson();
						try {
							if (type == String.class) {
								callback.onSuccess(statusCode, responseString);
							} else {
								callback.onSuccess(statusCode,
										mGson.fromJson(responseString, type));
							}

						} catch (Exception e) {
							e.printStackTrace(System.err);
							callback.onFailure(RESOLUTION_EXCEPTION,
									"解析出错");
						}

					}else{
						// 请求失败
						String rb = json.getString("desc");

						if (TextUtils.isEmpty(rb)) {
							rb = "网络异常，请您检查网络状态";
							callback.onFailure(code, rb);
						} else {
							callback.onFailure(code, rb);
						}
					}
				} catch (Exception e) {
					e.printStackTrace(System.err);
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) {

				if (responseBody != null && responseBody.length > 0) {
					if (400 <= statusCode && statusCode < 505) {
						String rb = "网络异常，请您检查网络状态";
						callback.onFailure(statusCode, rb);
					} else {
						String sb = new String(responseBody);
						callback.onFailure(statusCode, sb);
					}
				} else {
					String rb = "网络异常，请您检查网络状态";
					callback.onFailure(statusCode, rb);
				}

			}
		});
	}

	/************************************
	 * 
	 * 发送请求，并且只解析data字段,保证失败返回的描述严格不为空
	 * 
	 *******************************/
	public void post2Core(String repaymentDetail, RequestParams params,final HttpCallBack callback,
			final Type type) {

		if (!AppUtil.isConnect(BaseApplication.getInstance())) {
			callback.onFailure(NO_NET, "似乎没有网络");
			return;
		}
		client.post(repaymentDetail, params, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] responseBody) {

				try {
					String responseString = new String(responseBody);
					LogUtil.e("responseString", responseString);
					JSONObject res = new JSONObject(responseString);

					int code = res.getInt("code");
					if (code == SUCCESS) {
						// 请求成功
						try {
							Gson mGson = new Gson();
							String json = "";
							if (res.has("data")) {
								json = res.get("data").toString();
							}
							try {
								if (type == String.class) {
									callback.onSuccess(code, json);
								} else {
									callback.onSuccess(code,
											mGson.fromJson(json, type));
								}
							} catch (Exception e) {
								e.printStackTrace(System.err);
							}

						} catch (Exception e) {
							e.printStackTrace(System.err);
							String rb = "解析出错";
							callback.onFailure(RESOLUTION_EXCEPTION, rb);
						}
					} else if (code == TOKEN_OUT) {
						callback.onFailure(code, "token失效");
						// token失效了，跳转到登陆界面
						PreferenceUtils.getInstance().clearSharedPreferences(
								BaseApplication.getInstance());
						User.delCurUser();
						BaseApplication.getInstance().exitGestureActivity();
						Intent intent = new Intent(BaseApplication
								.getInstance(), LoginActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
								| Intent.FLAG_ACTIVITY_NEW_TASK);
						BaseApplication.getInstance().startActivity(intent);
					} else {
						// 请求失败
						String rb = res.getString("desc");

						if (TextUtils.isEmpty(rb)) {
							rb = "网络异常，请您检查网络状态";
							callback.onFailure(code, rb);
						} else {
							callback.onFailure(code, rb);
						}
					}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					String rb = "网络异常，请您检查网络状态";
					callback.onFailure(RESOLUTION_EXCEPTION, rb);
				}

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) {
				if (responseBody != null && responseBody.length > 0) {
					if (400 <= statusCode && statusCode < 505) {
						String rb = "网络异常，请您检查网络状态";
						callback.onFailure(statusCode, rb);
					} else {
						String sb = new String(responseBody);
						callback.onFailure(statusCode, sb);
					}
				} else {
					String rb = "网络异常，请您检查网络状态";
					callback.onFailure(statusCode, rb);
				}

			}

		});
	}

	public void get(String repaymentDetail, final Type type,
			final HttpCallBack callback) {

		if (!AppUtil.isConnect(BaseApplication.getInstance())) {
			callback.onFailure(NO_NET, "似乎没有网络");
			return;
		}
		client.get(repaymentDetail, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] responseBody) {

				try {
					String responseString = new String(responseBody);
					LogUtil.e("responseString", responseString);
					JSONObject res = new JSONObject(responseString);
					int code = res.getInt("code");
					if (code == SUCCESS) {
						// 请求成功
						try {
							Gson mGson = new Gson();
							String json = "";
							if (res.has("data")) {
								json = res.get("data").toString();
							}
							try {
								if (type == String.class) {
									callback.onSuccess(code, json);
								} else {
									callback.onSuccess(code,
											mGson.fromJson(json, type));
								}
							} catch (Exception e) {
								e.printStackTrace(System.err);
							}

						} catch (Exception e) {
							e.printStackTrace(System.err);
							String rb = "解析出错";
							callback.onFailure(RESOLUTION_EXCEPTION, rb);
						}
					} else if (code == TOKEN_OUT) {
						// token失效了，跳转到登陆界面
						callback.onFailure(code, "token失效");
						PreferenceUtils.getInstance().clearSharedPreferences(
								BaseApplication.getInstance());
						User.delCurUser();
						Intent intent = new Intent(BaseApplication
								.getInstance(), LoginActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
								| Intent.FLAG_ACTIVITY_NEW_TASK);
						BaseApplication.getInstance().startActivity(intent);
						PreferenceUtils.clear(BaseApplication.getInstance());
					} else {
						// 请求失败
						String rb = res.getString("desc");

						if (TextUtils.isEmpty(rb)) {
							rb = "网络异常，请您检查网络状态";
							callback.onFailure(code, rb);
						} else {
							callback.onFailure(code, rb);
						}
					}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					String rb = "网络异常，请您检查网络状态";
					callback.onFailure(RESOLUTION_EXCEPTION, rb);
				}

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) {
				if (responseBody != null && responseBody.length > 0) {
					if (400 <= statusCode && statusCode < 505) {
						String rb = "网络异常，请您检查网络状态";
						callback.onFailure(statusCode, rb);
					} else {
						String sb = new String(responseBody);
						callback.onFailure(statusCode, sb);
					}
				} else {
					String rb = "网络异常，请您检查网络状态";
					callback.onFailure(statusCode, rb);
				}

			}

		});
	}
	
	
	public void cancelRequestsByTAG(Object REQUEST_TAG) {
		client.cancelRequestsByTAG(REQUEST_TAG, true);
    }

	public void cancelAllRequests() {
		client.cancelAllRequests(true);
    }

}
